/****************************************************************
 *
 *  Add some comments here
 * 
 * 
 * 
 * 
 ***************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Wicresoft.OmsClient.OmsService;

namespace Wicresoft.OmsClient
{
    class ReminderSync
    {
        private Thread thrSync;

        public ReminderSync()
        {
            thrSync = new Thread(new ThreadStart(Main));
        }

        public void StartService()
        {
            if (thrSync == null)
                thrSync = new Thread(new ThreadStart(Main));
            thrSync.Start();
        }

        public void StopService()
        {
            thrSync.Abort();
        }

        private static void Main()
        {
            OMSService oms = new OMSService();
            while (true)
            {
                int syncinterval = SyncConfigManage.SyncInterval * 1000;
                try
                {
                    if (SyncConfigManage.EnableCalendarSync.ToLower() != "true" || !UserService.IsAuthorized)
                    {
                        Thread.Sleep(syncinterval);
                        continue;
                    }
                    string url = SyncConfigManage.ProviderUrl;
                    string email = SyncConfigManage.Email;
                    string mobile = SyncConfigManage.Mobile;
                    if (url == "" || email == "" || mobile == "")
                    {
                        if (url == "")
                        {
                          //  StateLight.Gray();
                        }
                        Thread.Sleep(syncinterval);
                        continue;
                    }
                    reminderData rd = new reminderData();
                    rd.user = new reminderDataUser();
                    rd.user.Owner = email;
                    rd.user.Mobile = mobile;
                    Logger.Debug("Start GetReminders");
                    rd.reminder = ReminderGetter.GetReminders();
                    Logger.Debug("End GetReminders");

                    if (rd.reminder.Length == 0)
                    {
                        Thread.Sleep(syncinterval);
                        continue; 
                    }

                    string xml = XmlBuilder.XmlSerializer<reminderData>(rd);
                    oms.Url = url;
                    oms.SetReminder(email, mobile, xml);
                   // StateLight.Green();

                }
                catch (Exception ex)
                {
                   // StateLight.Red();                    
                    Logger.Exception("sync thread Main Exception", ex);
                }                

                Thread.Sleep(syncinterval);
            }
        }
    }
}
